package com.ruoyi.member;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.appletsutil.AppletsLoginUtils;
import com.ruoyi.common.constant.Rediskey;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ThreadTask;
import com.ruoyi.common.utils.WeChatAppletUtils;
import com.ruoyi.integral.domain.CustomerPoint;
import com.ruoyi.integral.service.CustomerPointService;
import com.ruoyi.member.domain.UmsMember;
import com.ruoyi.member.vo.RunDataParam;
import com.ruoyi.member.vo.RunDataVo;
import com.ruoyi.setting.domain.LsStationLetter;
import com.ruoyi.setting.service.ILsStationLetterService;
import com.ruoyi.sms.domain.TStepData;
import com.ruoyi.sms.service.ITStepDataService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by 魔金商城 on 18/7/3
 * 我的运动控制器
 */
@Slf4j
@Api(description = "我的运动接口")
@RestController
public class StepDataController extends BaseController {


    @Autowired
    private ITStepDataService stepDataService;
    /**
     * 注入会员积分服务
     */
    @Autowired
    private CustomerPointService customerPointService;

    @Autowired
    private ILsStationLetterService letterService;
    /**
     * 注入redis服务
     */
    @Autowired
    private RedisCache redisService;
    @PostMapping("/runData")
    public AjaxResult runData(@RequestBody RunDataParam wxEntity, HttpServletRequest request) {
        String encryptedData = wxEntity.getEncryptedData();
        String iv = wxEntity.getIv();
        String sessionKey = wxEntity.getSessionKey();
        if (encryptedData == null && iv == null && sessionKey == null) {
            return AjaxResult.error("错误，没有数据");
        }
        String decrypt = null;
        //解密
        try {
            decrypt = WeChatAppletUtils.decryptWeChatRunInfo(sessionKey, encryptedData, iv);
        } catch (Exception e) {
            return AjaxResult.error("解密失败");
        }

        if (decrypt == null) {
            log.info("解密失败");
        } else {
            log.info("解析成功");
        }
        SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd");
        JSONObject stepInfoListJson = JSON.parseObject(decrypt);
        //解析json，获取stepInfoList下面的步数
        JSONArray stepInfoList = JSON.parseArray(stepInfoListJson.getString("stepInfoList"));

        //获取今天的步数
        JSONObject today = Objects.requireNonNull(stepInfoList).getJSONObject(30);
        List<RunDataVo> list = stepInfoList.toJavaList(RunDataVo.class);
        UmsMember member = AppletsLoginUtils.getInstance().getCustomer(request);
        ThreadTask.getInstance().addTask(() -> {
            stepDataService.deleteTStepDataByUserId(member.getId());
            for (RunDataVo vo: list){
                TStepData data = new TStepData();
                data.setCreateDate(new Date());
                data.setStep(vo.getStep());
                data.setUserId(member.getId());
                data.setUserName(member.getNickname());

                data.setData(format.format(vo.getTimestamp()*1000));
                stepDataService.insertTStepData(data);
            }
        });
        Map<String,Object> map = new HashMap<>();
        map.put("currentStep",today.getLongValue("step"));
        Long  userdStep = 0L;
        String userdStepStr =  redisService.getValue(String.format(Rediskey.USERED_STEP,format.format(new Date())+"-"+member.getId()));
        if (!StringUtils.isEmpty(userdStepStr)){
            userdStep=Long.parseLong(userdStepStr);
        }
        map.put("allowStep",today.getLongValue("step")-userdStep);
        return AjaxResult.success(map);
    }


    @RequestMapping(value = "/queryStepData")
    @ResponseBody
    public AjaxResult queryStepData(HttpServletRequest request, TStepData tStepData) {
        startPage();
        tStepData.setUserId(AppletsLoginUtils.getInstance().getCustomerId(request));
        List<TStepData> list = stepDataService.selectTStepDataList(tStepData);
        return AjaxResult.success(getDataTable(list));
    }

    @RequestMapping(value = "/selectOrderBYStep")
    @ResponseBody
    public AjaxResult selectOrderBYStep() {
        return AjaxResult.success(stepDataService.selectOrderBYStep());
    }
    @RequestMapping(value = "/stepToBlance")
    @ResponseBody
    public AjaxResult stepToBlance(HttpServletRequest request) {
        Long userId = AppletsLoginUtils.getInstance().getCustomerId(request);
        TStepData tStepData = new TStepData();
        tStepData.setUserId(userId);
        List<TStepData> list = stepDataService.selectTStepDataList(tStepData);
        SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd");

        if (list!=null && list.size()>0){
            Long step = list.get(0).getStep();
            Long  userdStep = 0L;
            String userdStepStr =  redisService.getValue(String.format(Rediskey.USERED_STEP,format.format(new Date())+"-"+userId));
            if (!StringUtils.isEmpty(userdStepStr)){
                userdStep=Long.parseLong(userdStepStr);
            }
            if ((step-userdStep)<1001){
                return AjaxResult.error("步数不够1000，不能兑换");
            }
            long blance = (step-userdStep)/1000;
            long newUserdStep = userdStep+blance*1000L;
            redisService.putToRedis(String.format(Rediskey.USERED_STEP,format.format(new Date())+"-"+userId),newUserdStep+"");
            LsStationLetter letter = new LsStationLetter();
            letter.setCustomerId(userId);
            letter.setDelFlag(1);
            letter.setTitle("步数兑换积分：" + blance);
            letter.setContent((step-userdStep)+"步数,兑换积分：" + blance);
            letter.setCreateTime(new Date());
            letterService.insertLsStationLetter(letter);
            //赠送积分
            logger.info("stepToBlance success : present point");
            customerPointService.addCustomerPoint(CustomerPoint.buildForStepDonate(userId, (int) blance));
            return AjaxResult.success(blance);
        }
        return AjaxResult.error();
    }

}
